import 'package:flutter/material.dart';
import 'package:window_manager/window_manager.dart';

/// 自定义标题栏组件
class CustomTitleBar extends StatefulWidget {
  final String title;
  final Color? backgroundColor;
  final Color? foregroundColor;
  final List<Widget>? actions;

  const CustomTitleBar({
    Key? key,
    required this.title,
    this.backgroundColor,
    this.foregroundColor,
    this.actions,
  }) : super(key: key);

  @override
  State<CustomTitleBar> createState() => _CustomTitleBarState();
}

class _CustomTitleBarState extends State<CustomTitleBar> {
  bool _isHovered = false;
  bool _isMaximized = false;

  @override
  void initState() {
    super.initState();
    _checkMaximized();
  }

  Future<void> _checkMaximized() async {
    final isMaximized = await windowManager.isMaximized();
    if (mounted) {
      setState(() {
        _isMaximized = isMaximized;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    final backgroundColor = widget.backgroundColor ?? Colors.grey[50];
    final foregroundColor = widget.foregroundColor ?? Colors.grey[900];

    return Container(
      height: 48,
      decoration: BoxDecoration(
        color: backgroundColor,
        border: Border(bottom: BorderSide(color: Colors.grey[300]!, width: 1)),
      ),
      child: Row(
        children: [
          // 左侧：应用图标和标题
          Expanded(
            child: GestureDetector(
              onPanStart: (details) {
                windowManager.startDragging();
              },
              onDoubleTap: () async {
                if (await windowManager.isMaximized()) {
                  windowManager.unmaximize();
                } else {
                  windowManager.maximize();
                }
              },
              child: MouseRegion(
                cursor: SystemMouseCursors.click,
                child: Container(
                  padding: const EdgeInsets.symmetric(horizontal: 16),
                  color: Colors.transparent,
                  child: Row(
                    children: [
                      // 应用图标
                      Container(
                        width: 24,
                        height: 24,
                        decoration: BoxDecoration(
                          color: Colors.blue,
                          borderRadius: BorderRadius.circular(6),
                        ),
                        child: const Icon(
                          Icons.extension,
                          color: Colors.white,
                          size: 16,
                        ),
                      ),
                      const SizedBox(width: 12),
                      // 标题
                      Text(
                        widget.title,
                        style: TextStyle(
                          fontSize: 14,
                          fontWeight: FontWeight.w600,
                          color: foregroundColor,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ),

          // 中间：自定义操作按钮
          if (widget.actions != null) ...widget.actions!,

          // 右侧：窗口控制按钮
          _buildWindowControls(foregroundColor!),
        ],
      ),
    );
  }

  Widget _buildWindowControls(Color foregroundColor) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        // 最小化按钮
        _WindowButton(
          icon: Icons.minimize,
          color: foregroundColor,
          onTap: () {
            windowManager.minimize();
          },
          tooltip: '最小化',
        ),

        // 最大化/还原按钮
        _WindowButton(
          icon: _isMaximized ? Icons.fullscreen_exit : Icons.crop_square,
          color: foregroundColor,
          onTap: () async {
            if (await windowManager.isMaximized()) {
              await windowManager.unmaximize();
              setState(() {
                _isMaximized = false;
              });
            } else {
              await windowManager.maximize();
              setState(() {
                _isMaximized = true;
              });
            }
          },
          tooltip: _isMaximized ? '还原' : '最大化',
        ),

        // 关闭按钮
        _WindowButton(
          icon: Icons.close,
          color: foregroundColor,
          hoverColor: Colors.red,
          onTap: () {
            windowManager.close();
          },
          tooltip: '关闭',
        ),

        const SizedBox(width: 8),
      ],
    );
  }
}

/// 窗口控制按钮
class _WindowButton extends StatefulWidget {
  final IconData icon;
  final Color color;
  final Color? hoverColor;
  final VoidCallback onTap;
  final String tooltip;

  const _WindowButton({
    Key? key,
    required this.icon,
    required this.color,
    this.hoverColor,
    required this.onTap,
    required this.tooltip,
  }) : super(key: key);

  @override
  State<_WindowButton> createState() => _WindowButtonState();
}

class _WindowButtonState extends State<_WindowButton> {
  bool _isHovered = false;

  @override
  Widget build(BuildContext context) {
    return Tooltip(
      message: widget.tooltip,
      waitDuration: const Duration(milliseconds: 500),
      child: MouseRegion(
        onEnter: (_) => setState(() => _isHovered = true),
        onExit: (_) => setState(() => _isHovered = false),
        cursor: SystemMouseCursors.click,
        child: GestureDetector(
          onTap: widget.onTap,
          child: Container(
            width: 46,
            height: 48,
            color: _isHovered
                ? (widget.hoverColor ?? Colors.grey[200])
                : Colors.transparent,
            child: Center(
              child: Icon(
                widget.icon,
                size: 18,
                color: _isHovered && widget.hoverColor != null
                    ? Colors.white
                    : widget.color,
              ),
            ),
          ),
        ),
      ),
    );
  }
}
